package com.common.scan;

import com.google.common.reflect.ClassPath;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;

public class GuavaScanClass {

    /**
     * 搜索包及子包下的Class
     * @param packageName 包路径 eg: com.xxx.yyy
     * @param clazzType
     * @return
     * @throws IOException
     */
    public Set<Class> findClasses(String packageName, ClazzType clazzType) throws IOException {
        return ClassPath.from(ClassLoader.getSystemClassLoader())
                .getAllClasses()
                .stream()
                .filter(clazz -> {
                    boolean flagClazz = StringUtils.startsWith(clazz.getPackageName(), packageName);
                    if (!flagClazz){
                        return false;
                    }
                    if (ClazzType.ENUM == clazzType){
                        return clazz.load().isEnum();
                    } else if (ClazzType.ANNOTATION == clazzType){
                        return clazz.load().isAnnotation();
                    }  else if (ClazzType.ALL == clazzType){
                        return true;
                    } else {
                        return false;
                    }
                })
                .map(clazz -> clazz.load())
                .collect(Collectors.toSet());
    }

}
